package io.qifan.desktop.client.event;

import io.qifan.desktop.api.auth.TokenUtil;
import io.qifan.desktop.api.device.DeviceDto;
import io.qifan.desktop.api.device.DeviceFeignClient;
import io.qifan.desktop.client.store.device.DeviceStore;
import io.qifan.desktop.client.store.token.TokenStore;
import io.qifan.desktop.common.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class LoginSuccessEventListener {
    @Autowired
    DeviceFeignClient deviceFeignClient;
    @Autowired
    TokenStore tokenStore;

    /**
     * 存储登录返回的token
     *
     * @param loginSuccessEvent
     */
    @EventListener
    @Order(0)
    public void handleLoginSuccessForTokenStorage(Events.LoginSuccessEvent loginSuccessEvent) {
        tokenStore.setToken(loginSuccessEvent.getToken());
        TokenUtil.tokenName = loginSuccessEvent.getToken().getTokenName();
        TokenUtil.tokenValue = loginSuccessEvent.getToken().getTokenValue();
    }

    /**
     * 记录当前设备，并初始化设备id和密码
     *
     * @throws UnknownHostException
     */
    @EventListener(Events.LoginSuccessEvent.class)
    @Order(1)
    public void handleLoginForDeviceInit() throws UnknownHostException {
        String hostName = InetAddress.getLocalHost().getHostName();
        R<DeviceDto> deviceDtoR = deviceFeignClient.findByName(hostName);
        DeviceStore.currentDevice = deviceDtoR.getResult();
    }


}
